package com.lty.jeeg.server.modules.fas.service.impl;

import com.lty.jeeg.server.common.enums.ResponseEnum;
import com.lty.jeeg.server.common.page.table.PageTableHandler;
import com.lty.jeeg.server.common.page.table.PageTableRequest;
import com.lty.jeeg.server.common.page.table.PageTableResponse;
import com.lty.jeeg.server.common.utils.BeanConverter;
import com.lty.jeeg.server.common.utils.UserUtil;
import com.lty.jeeg.server.modules.fas.dao.GoodsCategoryDao;
import com.lty.jeeg.server.modules.fas.dao.GoodsDao;
import com.lty.jeeg.server.modules.fas.dto.GoodsCategoryDTO;
import com.lty.jeeg.server.modules.fas.dto.GoodsDTO;
import com.lty.jeeg.server.modules.fas.dto.StockDTO;
import com.lty.jeeg.server.modules.fas.export.StockExportEntity;
import com.lty.jeeg.server.modules.fas.export.StockExportEntityDP;
import com.lty.jeeg.server.modules.fas.export.StockImportEntityDP;
import com.lty.jeeg.server.modules.fas.service.GoodsCategoryService;
import com.lty.jeeg.server.modules.fas.service.GoodsService;
import com.lty.jeeg.server.modules.sys.dao.DeptDao;
import com.lty.jeeg.server.modules.sys.dao.DictDao;
import com.lty.jeeg.server.modules.sys.dao.UserDao;
import com.lty.jeeg.server.modules.sys.model.Dept;
import com.lty.jeeg.server.modules.sys.model.Dict;
import com.lty.jeeg.server.modules.sys.model.User;
import com.lty.jeeg.server.modules.sys.service.impl.BaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.lty.jeeg.server.modules.fas.dao.StockDao;
import com.lty.jeeg.server.modules.fas.model.Stock;
import com.lty.jeeg.server.modules.fas.service.StockService;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @author : LTY
 * @date : 2019-02-13 10:11:33
 * Description : 库存统计
 */
@Service
@Slf4j
public class StockServiceImpl implements StockService {

    private final StockDao stockDao;
    private final GoodsDao goodsDao;
    private final UserDao userDao;
    private final DeptDao deptDao;
    private final DictDao dictDao;
    private final GoodsCategoryDao goodsCategoryDao;
    private final GoodsService goodsService;
    private final GoodsCategoryService goodsCategoryService;

    @Autowired
    public StockServiceImpl(StockDao stockDao, GoodsDao goodsDao, UserDao userDao, DeptDao deptDao, DictDao dictDao, GoodsCategoryDao goodsCategoryDao, GoodsService goodsService, GoodsCategoryService goodsCategoryService) {

        this.stockDao = stockDao;
        this.goodsDao = goodsDao;
        this.userDao = userDao;
        this.deptDao = deptDao;
        this.dictDao = dictDao;
        this.goodsCategoryDao = goodsCategoryDao;
        this.goodsService = goodsService;
        this.goodsCategoryService = goodsCategoryService;
    }

    @Override
    public StockDTO getById(Long id) {

        return stockDao.getById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delete(Long id) {
        log.debug("删除Stock=>{}", id);
        return stockDao.delete(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int update(Stock stock) {
        stock.preUpdate();
        GoodsDTO goodsDTO = goodsService.getById(stock.getGoodsId());
        GoodsCategoryDTO goodsCategoryDTO = goodsCategoryService.getById(goodsDTO.getCategory());
        stock.setParentCategory(goodsCategoryDTO.getParentId());
        log.debug("修改Stock=>{}", stock.getId());
        return stockDao.update(stock);
    }

    @Override
    public ResponseEnum updateIdle(HttpServletRequest request) {
        //需求明细Id
        String orderDetailId = request.getParameter("orderDetailId");
        //闲置数量
        String idleNumber = request.getParameter("idleNumber");
        if (orderDetailId != null) {
            Stock stock = stockDao.getById(Long.parseLong(orderDetailId));
            if (stock.getTotalNumber() < Integer.parseInt(idleNumber)) {
                return ResponseEnum.STOCK_IDLE_NUMBER_ERROR;
            } else {
                stockDao.updateIdle(Long.parseLong(orderDetailId), idleNumber);
                return ResponseEnum.SUCCESS;
            }

        } else {
            return ResponseEnum.ERROR;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long save(Stock stock) {
        stock.preInsert();
        //页面不显示商品分类了，在这里关联出来保存上
        Long goodId = stock.getGoodsId();
        GoodsDTO goodsDTO = goodsService.getById(goodId);
        Long categoryId = goodsDTO.getCategory();
        GoodsCategoryDTO goodsCategoryDTO = goodsCategoryService.getById(categoryId);
        Long parentCategory = goodsCategoryDTO.getParentId();
        stock.setParentCategory(parentCategory);
        stock.setCategory(categoryId);
        //判断部门库或个人库下是否有这个商品了
        Long id = null;
        //个人库
        if (!StringUtils.isEmpty(stock.getUserId()) && !StringUtils.isEmpty(stock.getDeptId())) {
            id = stockDao.getIdForPer(stock);
        }
        //部门库
        if (StringUtils.isEmpty(stock.getUserId()) && !StringUtils.isEmpty(stock.getDeptId())) {
            id = stockDao.getIdForDept(stock);
        }
        //如果对应库里有此类商品，更改商品的总数量和闲置数量
        if (id != null) {
            StockDTO dto = stockDao.getById(id);
            stock.setId(id);
            stock.setTotalNumber(stock.getTotalNumber() + dto.getTotalNumber());
            stock.setIdleNumber(stock.getIdleNumber() == null ? 0 : stock.getIdleNumber() + dto.getIdleNumber());
            stockDao.update(stock);
            log.debug("修改Stock=>{}", stock.getId());
        } else {
            if (stock.getIdleNumber() == null) {
                stock.setIdleNumber(0);
            }
            stockDao.save(stock);
            log.debug("新增Stock=>{}", stock.getId());
        }

        return stock.getId();
    }

    @Override
    public PageTableResponse list(PageTableRequest request) {
        request.getParams().put("dsf", BaseService.dataScopeFilter("fas", UserUtil.getCurrentUser(), "du", "ua"));
        return new PageTableHandler(
                request1 -> stockDao.count(request1.getParams()),
                request2 -> stockDao.query(
                        request2.getParams(), request2.getOffset(), request2.getLimit()))
                .handle(request);
    }

    /**
     * 导出查询数据
     *
     * @param stockDTO StockDTO
     * @return 导出数据list
     */
    @Override
    public List<StockExportEntity> getExportDatas(StockDTO stockDTO) {
        return stockDao.getExportDatas(stockDTO);
    }

    /**
     * 导出查询数据(个人库存列表和部门库存列表)
     *
     * @param stockDTO
     * @return
     */
    @Override
    public List<StockExportEntityDP> getExportDatasDP(StockDTO stockDTO) {
        return stockDao.getExportDatasDP(stockDTO);
    }

    @Override
    public Stock gets(Long goodsId, Long deptidcome) {
        return stockDao.getByGoodsIdAndDeptId(goodsId, deptidcome);
    }

    /**
     * 导入库存信息
     *
     * @param stockList
     * @return
     */
    @Override
    public List<StockImportEntityDP> importData(List<Object> stockList) {
        //导入失败List
        List<StockImportEntityDP> failList = new ArrayList<>();
        //处理数据
        if (stockList != null && stockList.size() > 0) {
            for (Object obj : stockList) {
                StockImportEntityDP stockImportEntityDP = (StockImportEntityDP) obj;
                boolean flag = true;
                StringBuilder sb = new StringBuilder();
                //校验数据
                //商品编码
                String goodsCode = stockImportEntityDP.getGoodsCode();
                //所属人员
                String userName = stockImportEntityDP.getUserName();
                //所属部门
                String deptName = stockImportEntityDP.getDeptName();
                //所属公司
                String companyName = stockImportEntityDP.getCompanyName();
                //总数量
                String totalNumber = stockImportEntityDP.getTotalNumber();
                GoodsDTO goodsDTO = new GoodsDTO();
                User user = new User();
                Dept dept = new Dept();

                //编码
                if (!StringUtils.isEmpty(goodsCode)) {
                    //判断编码是否填写正确
                    goodsDTO = goodsDao.getByCode(goodsCode);
                    if (goodsDTO != null && goodsDTO.getId() != null) {
                        //判断该商品是否是非常规商品
                        if (goodsDTO.getIsCommon() != null && goodsDTO.getIsCommon() == 0) {
                            //非常规物品必须有所属人员
                            if (StringUtils.isEmpty(userName)) {
                                flag = false;
                                sb.append("非常规商品必须拥有所属人员;");
                            }
                        }
                    } else {
                        //商品编码填写错误
                        flag = false;
                        sb.append("商品编码填写错误,请核对;");
                    }
                } else {
                    //编码为空
                    flag = false;
                    sb.append("商品编码不能为空;");
                }

                Dict company = dictDao.getByTypeAndVal("company", companyName);
                if (company != null) {
                    //部门和公司
                    dept = deptDao.getByNameAndCompany(deptName, company.getK());
                    if (dept != null && dept.getId() != null) {
                        //校验填写所属人员是否在当前部门
                        //所属用户可以为空
                        if (!StringUtils.isEmpty(userName)) {
                            //所属人员如果填写必须正确
                            user = userDao.getUser(userName);
                            if (user != null && user.getId() != null) {
                                Dept userDept = user.getDept();
                                if (userDept != null && userDept != null) {
                                    if (!userDept.getId().equals(dept.getId())) {
                                        flag = false;
                                        sb.append("当前所属人员不属于该部门,请核对;");
                                    }
                                } else {
                                    flag = false;
                                    sb.append("找不到当前所属人员的部门,请核对;");
                                }
                            } else {
                                flag = false;
                                sb.append("找不到该所属人员(请参考系统用户名填写);");
                            }
                        }
                    } else {
                        flag = false;
                        sb.append("公司或部门为空或填写错误,请核对;");
                    }
                } else {
                    flag = false;
                    sb.append("公司为空或填写错误,请核对;");
                }

                //数量 TODO 使用正则校验下
                if (!StringUtils.isEmpty(totalNumber)) {
                    try {
                        Integer totalNum = Integer.valueOf(totalNumber);
                    } catch (Exception e) {
                        flag = false;
                        sb.append("总数量必须为整数;");
                    }
                } else {
                    flag = false;
                    sb.append("总数量不能为空;");
                }

                if (flag) {
                    //校验成功
                    //如果填写用户,查询当前用户名下是否有当前商品库存
                    if (!StringUtils.isEmpty(userName)) {
                        //查询当前用户名下是否有当前商品库存
                        Long stockId = stockDao.getIdByUserLib(goodsDTO.getId(), user.getId(), dept.getId());
                        StockDTO stockDTO = new StockDTO();
                        if (stockId != null) {
                            stockDTO = stockDao.getById(stockId);
                        }
                        if (stockDTO != null && stockDTO.getId() != null) {
                            //当前用户拥有该商品,修改数量保存
                            //增加库存数量
                            stockDTO.setTotalNumber(stockDTO.getTotalNumber() + Integer.valueOf(totalNumber));
                            stockDao.update(BeanConverter.map(stockDTO, Stock.class));
                            log.debug("导入Stock=>{}", stockDTO.getId());
                        } else {
                            //当前用户没有该商品,新增库存记录
                            //新建库存记录
                            Stock newStock = new Stock();
                            newStock.preInsert();
                            //商品
                            newStock.setGoodsId(goodsDTO.getId());
                            Long goodsCategoryId = goodsDTO.getCategory();
                            GoodsCategoryDTO goodsCategoryDTO = goodsCategoryDao.getById(goodsCategoryId);
                            Long parentCategory = goodsCategoryDTO.getParentId();
                            //商品类型父级
                            newStock.setParentCategory(parentCategory);
                            //商品类型
                            newStock.setCategory(goodsCategoryId);
                            //所属人员
                            newStock.setUserId(user.getId());
                            //所属部门
                            newStock.setDeptId(dept.getId());
                            //所属公司
                            newStock.setCompanyId(dept.getCompany());
                            //总数量
                            newStock.setTotalNumber(Integer.valueOf(totalNumber));
                            //闲置数量
                            newStock.setIdleNumber(0);
                            Long id = stockDao.save(newStock);
                            log.debug("导入Stock=>{}", id);
                        }
                    } else {
                        //查询当前部门下是否有当前商品库存
                        Long stockId = stockDao.getIdByDeptLib(goodsDTO.getId(), dept.getId());
                        StockDTO stockDTO = new StockDTO();
                        if (stockId != null) {
                            stockDTO = stockDao.getById(stockId);
                        }
                        if (stockDTO != null && stockDTO.getId() != null) {
                            //当前部门下有该商品,修改数量保存
                            stockDTO.setTotalNumber(stockDTO.getTotalNumber() + Integer.valueOf(totalNumber));
                            stockDao.update(BeanConverter.map(stockDTO, Stock.class));
                            log.debug("导入Stock=>{}", stockDTO.getId());
                        } else {
                            //当前部门下没有该商品,新增库存记录
                            //新建库存记录
                            Stock newStock = new Stock();
                            newStock.preInsert();
                            //商品
                            newStock.setGoodsId(goodsDTO.getId());
                            Long goodsCategoryId = goodsDTO.getCategory();
                            GoodsCategoryDTO goodsCategoryDTO = goodsCategoryDao.getById(goodsCategoryId);
                            Long parentCategory = goodsCategoryDTO.getParentId();
                            //商品类型父级
                            newStock.setParentCategory(parentCategory);
                            //商品类型
                            newStock.setCategory(goodsCategoryId);
                            //所属部门
                            newStock.setDeptId(dept.getId());
                            //所属公司
                            newStock.setCompanyId(dept.getCompany());
                            //总数量
                            newStock.setTotalNumber(Integer.valueOf(totalNumber));
                            //闲置数量
                            newStock.setIdleNumber(0);
                            Long id = stockDao.save(newStock);
                            log.debug("导入Stock=>{}", id);
                        }
                    }
                } else {
                    //导入失败
                    stockImportEntityDP.setFailMsg("失败信息：" + sb.toString());
                    failList.add(stockImportEntityDP);
                }
            }
        }
        return failList;
    }
}
